import React, { useEffect, useRef, useState, lazy, useImperativeHandle} from "react";
import { LayoutB } from "~/public/cpas-ui";
import type { MenuProps } from 'antd';
import { Button, Checkbox } from 'antd';
import { Progress } from 'antd';
import type { DataNode } from 'antd/es/tree';
import {
  Dropdown, message,
  Space, Tooltip, Modal, Table,
  Collapse,
  Spin,
  Input,
  Tree
} from 'antd';

import "./index.less";

import {
  getLeftTreeList,
  addTreeNodePage,
  delTreeNodePage,
  setEditTreeTittle,
  moveTreeNodePage,
  fetchReportList,
  getCpasTableName,
  editCpasTableNames,
  copyCpasTableFun,
  clearDataAll,
  queryDataState,
  queryResetState,
  queryVerifyStatezl,
  menuTemplateBatch, fetchAlwaysShow, getTemplateExportToSqlite,
  getNotesIsEmptyAPI,
  reCalculateNotesAPI,
  getAllTypeData,
} from "./server";
import CpasIcon from "~/public/cpas-ui/components-ui/components/Icon";
import CpasTableDs from "~/public/cpas-business/cpas-table/CpasTableDs";
import ContextMenu from 'devextreme-react/context-menu'
import TreeView from 'devextreme-react/tree-view';
import Sortable from 'devextreme-react/sortable';
import { getDataId, getZcbmId } from "~/public/cpas-business/tools/Tools"
import { CheckOutlined, PlusOutlined, SaveOutlined, WarningOutlined, WifiOutlined, LoadingOutlined } from '@ant-design/icons';
const Details = lazy(() => import("~/public/cpas-business/cpas-table/ExcelGrid/components/Validator/CheckDetails"))
// import { dataMenu } from "./data"
// import {Popup,ToolbarItem} from "devextreme-react/popup"
import TemplateModal from "~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup"
import TemplateSave from "~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup"
import { getSeekAuditReportTemplate, templateInitApi } from "../../unFinancialStatements/service";
import { getReportItemsZero, getTemplateInfo } from "../../../services/annotaionAnalysis";
import { resetPidIfNotFound, EntrySynchronizationMethod, sortTreeByChildren, loopParentTreeList } from '@/utils/index'

import notify from "devextreme/ui/notify";

import PageLoading from "../../components/PageLoading"
import _ from "lodash";
import { singleDSTableInit, queryCpasTableByMb } from "../../../services/annotaionAnalysis";
import { io } from "socket.io-client";
import { E_CpasTableDescCategory } from "~/public/cpas-business/cpas-table/CpasTableDs/CpasHandsonTableDs";
import { LoadPanel } from "devextreme-react/load-panel";
import ConfirmDialog from "./confirmDialog";
import { TextBox } from 'devextreme-react/text-box';
import ImportExcelModal from '~/public/cpas-business/cpas-table/CpasModal/ImportExcelModal';
import CpasModal from '~/public/cpas-business/cpas-table/CpasModal'
import BuildLaction from "./noteBuildLocation"
const { confirm } = Modal;
const { Search } = Input;
const { Panel } = Collapse;
const antIcon = <LoadingOutlined style={{ fontSize: 15 }} spin />;
export const NotePage: React.FC<any> =  React.forwardRef((props: any, ref: any) => {
  const { initialState, dataMenu } = props;
  const { dbname, zcbfid, zcbfName, sjnd, AuditReportTemplate, curUser } = initialState?.curPart;
  const { usercode } = initialState?.curUser;
  const userInfoStr = window.localStorage.cpasUserInfo;
  const userInfo = JSON.parse(userInfoStr);
  const password = window.main.cryptoUtil(userInfo.aesPassword);
  const leftTreeRef = useRef<any>();
  const dsTableRef = useRef<any>()
  const dsRef = useRef<any>()
  const templateRef = useRef<any>(null)
  const saveRef = useRef<any>(null);
  const importExcelRef = useRef<any>(null);
  const exportRef = useRef<any>(null);
  const curNodeRef = useRef<any>();
  const lastCurNodeRef = useRef<any>(); //用于记录上一次的节点
  const liftingNodeRef = useRef<any>();
  const [getTreesData, setTreesData] = useState<any>([]);
  const [treeDataList, setTreeDataList] = useState<any>([])
  const [dataName, setDataName] = useState<string>("")
  const [selectData, setSelectData] = useState<any>({})
  const [copyItemData, setCopyItemData] = useState<any>({})
  const [isModalOpen, setModalOpen] = useState<boolean>(false)
  const [isOpenWordlocation, setIsOpenWordlocation] = useState<boolean>(false)

  const [isShowOpen, setShowOpen] = useState<boolean>(false)
  const initStateSize = ["22%", "20px", "80%"]
  const stateSize = ["40px", "40px", "40px"]
  const [isState, setIsState] = useState<boolean>(true)
  const [isOpenEye, setOpenEye] = useState<boolean>(true)
  const [dataSource, setDataSource] = useState<any>([])
  const [pageLoading, setPageLoading] = useState(false)
  const [disclosure, setDisclosure] = useState(false)
  const [includeTables, setIncludeTables] = useState(false)
  const [level, setLevel] = useState(false)
  const [optionsData, setOptionsData] = useState([]);
  const [value, setValue] = useState();
  const [projectName, setProjectName] = useState("")
  const [openDetails, setOpenDetails] = useState(false)
  const [verifyResult, setVerifyResult] = useState<any>([])
  const [clickItem, setClickItem] = useState<any>({})
  const [noteProps, setNoteProps] = useState({})
  const [getDataIds, setDataIds] = useState(null)
  const [reportChecks, setReportChecks] = useState<any>([])

  const [popupShow, setPopupShow] = useState(false);
  const [templateModalShow, setTemplateModalShow] = useState(false);
  const [tableName, setTableName] = useState("")
  const [oldTableName, setOldTableName] = useState("")
  // const [importExcelModalShow, setImportExcelModalShow] = useState(false);
  const [importExcelList, setImportExcelList] = useState([]);
  const [menuItem, setMenuItem] = useState<any>({
    isScree: false,
    isAlwaysShow: false,
    isCollapse: false, //菜单是否折叠
  })
  const [dbOrExcel, setDbOrExcel] = useState("")
  const [menuList, setMenuList] = useState<DataNode[]>([])
  const [defaultCheckedKey, setDefaultCheckedKey] = useState<any>([]);
  const [checkedAll, setCheckedAll] = useState(false);
  const [contentText, setContent] = useState(false)
  const [percentNum, setPercentNum] = useState<any>(0)
  const [titleAndContent, setTitleAndContent] = useState<any>({
    title: "",
    content: ""
  })
  // const [renameModal, setRenameModal] = useState<boolean>(false)
  const [dir, setDir] = useState("")
  const [showTemplateOpen, setShowTemplateOpen] = useState<boolean>(false)
  const [contentMsg, setContentMsg] = useState("")
  const [btnLoading, setBtnLoading] = useState(false)
  const [btnLoadingId, setBtnLoadingId] = useState("")
  const [topIndex, setTopIndex] = useState(0)
  const [otherCheck, setOtherCheck] = useState(false)
  const [mainProject, setMainProject] = useState("")
  const { io } = require('socket.io-client');
  // lastScrollTop 用于记录上一次滚动条的位置
  const leftTreeScrollRef = useRef<any>(0);
  const [loadingTimerId, setLoadingTimer] = useState<any>(null);
  const [templateLoadPanelVisible, setTemplateLoadPanelVisible] = useState<boolean>(false);
  //const [checkedNotesTids, setCheckedNotesTids] = useState<any>([]);
  const confirmDialogRef = useRef<any>(); // 模板
  const [isSyncStatus, setIsSyncStatus] = useState("1"); // 1:初始化 2:进行中 3已完成
  const [searchValue, setSearchValue] = useState("");
  const [isRightTemplateAdd, setIsRightTemplateAdd] = useState(false); //是否是右键模版库添加
  const reportLocation = useRef<any>(); // 报告位置
  const locationName = useRef<any>(); // 报告位置

  // 获取年度值
  const getYearData = async () => {
    const data = await getDataId()
    setDataIds(data)
  }

  const getCpasDescByCategory = (category: string, cpasDesc: any) => {
    if (!cpasDesc || cpasDesc.length === 0) {
      return null
    }
    for (let i = 0; i < cpasDesc.length; i++) {
      const item = cpasDesc[i];
      if (item.category === category) {
        return item;
      }
    }
    return null;
  }

  useEffect(() => {
    const cpasApiUrl = localStorage.getItem("cpasApiUrl");
    const apiUrl = cpasApiUrl && cpasApiUrl.includes("cpasApi") ? cpasApiUrl.replace("/cpasApi", "") : cpasApiUrl;
    const socket = io(apiUrl, {
      connectionStateRecovery: {
        // the backup duration of the sessions and the packets
        maxDisconnectionDuration: 2 * 60 * 1000,
        // whether to skip middlewares upon successful recovery
        skipMiddlewares: true,
      },
      auth: {
        name: "notes"
      }
    });
    socket.on('connect', () => {
      const engine = socket.io.engine;
      console.log('socket connect: ', engine.transport.name); // in most cases, prints "polling"
      engine.on("close", (reason: any) => {
        // called when the underlying connection is closed
        console.log('socket close: ', reason);
      });
    });

    // either by directly modifying the `auth` attribute
    socket.on("connect_error", () => {
      console.log("connect_error 连接错误");
    });

    socket.io.on("reconnect_attempt", () => {
      console.log("reconnect_attempt 尝试重新连接");
    });

    socket.io.on("reconnect", () => {
      console.log("reconnect 尝试重新连接");
    });

    socket.on("disconnect", (reason: any) => {
      // ...
      console.log("disconnect 断开连接", reason);
    });

    socket.onAny((eventName: any, ...args: any) => {
      console.log(`on refresh onAny: ${eventName}`, args);
    });
    socket.on('notesSyncState', async (msg: any) => {
      console.log('on refresh ui event: ', msg);
      setIsSyncStatus("3");
      const res = msg ? JSON.parse(msg) : {};
      const args = res?.args || {};
      if (res.ok && (args?.tag === "note" || args?.tag === "singleNote")) {
        console.log('finish---loadingTimerId', loadingTimerId);
        clearTimeout(loadingTimerId);
        console.log(loadingTimerId, 'loadingTimerId page');
        let params = {
          dbname,
          data_id: getDataIds,
          type: "vr"
        };
        if (args?.tag === "singleNote" && curNodeRef?.current?.fid) {
          params["tids"] = [curNodeRef.current.fid];
        }
        await getAllTypeData(params);
        await initReload(curNodeRef.current.title);
        setPageLoading(false);
        notify("同步成功", "success")
      } else {
        // clearTimeout(loadingTimerId);
        setPageLoading(false);
        notify("同步失败", "error", 2000)
      }
    });
    return () => {
      console.log("socket.clsoe log");
      clearTimeout(loadingTimerId);
      socket.close();
    }
  }, [getTreesData, loadingTimerId])

  useEffect(() => {
    console.log(isSyncStatus, 'isSyncStatus----');
    if (isSyncStatus === "2") {
      setPageLoading(false);
    }
  }, [isSyncStatus]);
  const paramItem: any = {
    dbName: dbname,
    disclosureGroup: "",
    disclosureContent: "",
    disclosureContentNote: "",
    associatedReport: "",
    lastYearCount: false,
    isEmpty: false,
    isVerified: false,
    isDisclosure: true,
    isIncludeTable: true,
    isZeroReportCount: false,
    isAlwaysShow: false,
    isSetLevel: true,
    isVerify: null,
    // title: "新建披露表"+ Math.round(Math.random()*10+50),
    icon: "icon-biaogeyangshiku",
    config: {},
    dataId: getDataIds
  }
  // 初始化 默认选中第一条 加载第一条表格数据源
  // selTitle 指定选中的title数据
  const initReload = async (selTitle?: string, templateType?: string) => {
    const leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
    // 每次reload前记载一下上次的滚动条位置
    if (leftTreeViewScrollView) {
      leftTreeScrollRef.current = leftTreeViewScrollView.scrollTop();
    }
    setPageLoading(true)
    const dataId = await getDataId()
    const resData = await getLeftTreeList(dbname, dataId);
    // console.log(getTreesData, 'getTreesData initReload');
    if (resData.length > 0) {
      const data = resetPidIfNotFound(resData);
      const dataTree = data.map((item: any) => {
        if (item.isAlwaysShow) {
          defaultCheckedKey.push(item.id)
          setDefaultCheckedKey([...defaultCheckedKey])
        }
        const oldTree = getTreesData.filter((oldItem: any) => oldItem.fid === item.fid);
        // const oldParent = getTreesData.filter((oldItem: any) => oldItem.id ===item.pid );
        let isExpanded = false;
        if (localStorage.getItem('isExpanded') === "true" || (oldTree && oldTree[0]?.expanded)) {
          isExpanded = true;
        }
        const obj = {
          icon: "icon-biaogeyangshiku",
          parentId: item.pid,
          expanded: isExpanded,
          key: item.title,
          isDirectory: true,
          ...item
        }
        return obj
      })
      if (defaultCheckedKey.length === dataTree.length) {
        setCheckedAll(true)
      }
      let selData = data[0];
      data.map((item: any) => {
        if (selTitle && item.title === selTitle) {
          selData = item
        }
        item.key = item.title
      })
      setTreeDataList(data)
      setTreesData(dataTree)
      const tableData = await dsRef.current.loadTableByServer(selData.title, selData.dataId, selData.fid)
      const verifyData = await dsRef.current.loadVerifyByServer(selData.fid + "-zl")
      console.log("初始化整理下的勾稽详情", verifyData);

      const zlParams = {
        dbname,
        tid: selData.fid,
        type: "zl"
      }
      const lodaTableZl = await queryVerifyStatezl(zlParams)
      // dsRef.current.setVerifyData(verifyData)
      if (lodaTableZl.code === 200) {
        dsTableRef.current.zlTableRef.current.setVerifyData(verifyData)
        setVerifyResult(verifyData.artParseResultList)
      }
      const titleName =
        selData.isIncludeTable ?
          selData.title :
          <div>{selData.title}<span style={{ color: "red" }}>(此披露项目不包含表格)</span></div>
      setDataName(titleName)
      setSelectData(selData)
      const obj = {
        tid: selData.fid,
        data_id: selData.dataId,
      }
      setNoteProps(obj)
      curNodeRef.current = selData
      if (menuItem.isCollapse) {
        leftTreeRef?.current?.instance?.collapseAll()
      }
      // scrollToItem定位效果不佳
      if (selTitle) {
        setTimeout(() => {
          const n_leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
          n_leftTreeViewScrollView.scrollTo({ left: 0, top: leftTreeScrollRef.current });
        }, 300)
        // leftTreeRef?.current?.instance?.scrollToItem(selData.id);
      }
      if (tableData?.code === 500) {
        setPageLoading(false)
        setBtnLoading(false)
        await dsRef.current.resetTable("ds")
        await dsTableRef.current.zlTableRef.current.resetTable("zl")
        return message.error(tableData.msg)
      } else {
        console.log(tableData, 'tableData-----');
        await dsRef.current.reloadTable(tableData, null, null, true, true)
        const dc = getCpasDescByCategory(E_CpasTableDescCategory.DC, tableData.cpasDesc)
        const dcn = getCpasDescByCategory(E_CpasTableDescCategory.DCN, tableData.cpasDesc)
        dsTableRef.current.setTitleEditorContent(dc ? dc.describe : "");
        dsTableRef.current.setContentEditorContent(dcn ? dcn.describe : "");
        const zlTableConfig = dsTableRef?.current?.zlTableRef?.current?.tableConfig;
        //整理模式配置信息初始化
        if (zlTableConfig) {
          zlTableConfig.directionCfg = {
            direction: "vertical"
          };
          const delTableCfg = ["rowMergeCfg", "filterCfg", "sortCfg", "hideColumnKeyArr", "rule"];
          for (let i = 0; i < delTableCfg.length; i++) {
            if (zlTableConfig[delTableCfg[i]]) {
              delete zlTableConfig[delTableCfg[i]];
            }
          }
        }
        console.log(zlTableConfig, '整理模式配置信息 zlTableConfig----');
        if (+dsTableRef?.current?.state?.tabValue === 2) {
          dsTableRef.current.tabModelChanges("2");
        }
        setPageLoading(false)
      }
    } else {
      setDataName("")
      setBtnLoading(false)
      dsTableRef.current.setTitleEditorContent("")
      dsTableRef.current.setContentEditorContent("")
      setSelectData({})
      setNoteProps({})
      setTreesData([])
      setPageLoading(false)
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      if (templateType !== "switchTemplate") {
        initTemplate("");
      }
    }
  }
  // 自定义方法
  useImperativeHandle(ref, () => ({
    tab1Init: async () => {
      await initReload();
    },
    openVerifyDetail: (item: any, noVerifyModal: boolean) => {
      openDetail(null, item, noVerifyModal);
    },
    tab1SearchTableName(value: string, fid: string) {
      const currentData = getTreesData.filter((item: any) => item.fid === fid);
      if(currentData && currentData.length) {
        setSearchValue(currentData[0].title);
      }else {
        setSearchValue(value);
      }
    }
  }));
  const initContent = (param: boolean) => {
    setContent(param)
  }
  /**
   * 查询节点数据
   * @param isNoteSearch 是否是附注搜索调用
   * @returns
   */
  const getListsTree = async (isNoteSearch?: boolean, currentSearchVal?: string) => {
    const dataId = await getDataId()
    const leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
    // 每次reload前记载一下上次的滚动条位置
    if (leftTreeViewScrollView) {
      leftTreeScrollRef.current = leftTreeViewScrollView.scrollTop();
    }
    const resData = await getLeftTreeList(dbname, dataId);
    if (resData.length > 0) {
      const data = resetPidIfNotFound(resData);
      const dataTree = data.map((item: any) => {
        const oldTree = getTreesData.filter((oldItem: any) => oldItem.fid === item.fid);
        // const oldParent = getTreesData.filter((oldItem: any) => oldItem.id ===item.pid );
        let isExpanded = false;
        if (localStorage.getItem('isExpanded') === "true" || (oldTree && oldTree[0]?.expanded)) {
          isExpanded = true;
        }
        const obj = {
          parentId: item.pid,
          expanded: oldTree && oldTree[0]?.expanded ? true : false,
          key: item.title,
          isDirectory: oldTree && oldTree[0]?.isDirectory ? true : false,
          ...item
        }
        return obj
      })
      data.map((item: any) => {
        item.key = item.title
      })
      console.log(data, '附注节点加载');
      const val = currentSearchVal ? currentSearchVal : searchValue;
      if(isNoteSearch && val) {
        return dataTree;
      }else {
        setTreeDataList(data)
        setTreesData(dataTree)
        setTimeout(() => {
          const n_leftTreeViewScrollView = leftTreeRef?.current?.instance?.getScrollable();
          n_leftTreeViewScrollView.scrollTo({ left: 0, top: leftTreeScrollRef.current });
        }, 300)
      }
    }
    // console.log(dbTable);
  }

  // 新增节点数据
  const newAddTreeNode = async (params: any) => {
    setPageLoading(true)
    const newTreeNode: any = await addTreeNodePage(params);
    if (newTreeNode.ok) {
      setCopyItemData({})
      setClickItem({})
      setPopupShow(false)
      setDir("")
      const obj = {
        tid: newTreeNode.data.fid,
        data_id: newTreeNode.data.dataId,
        status_name: "add"
      }
      setNoteProps(obj)
      const saveData = await dsTableRef.current.handleSaveData(newTreeNode.data.title, newTreeNode.data.fid, newTreeNode.data.dataId, "add");
      dsTableRef.current.setTitleEditorContent("")
      dsTableRef.current.setContentEditorContent("")
      if (saveData?.code) {
        return message.error(saveData.msg)
      } else {
        setSelectData(newTreeNode.data)
        setDataName(newTreeNode.data.title)
        curNodeRef.current = newTreeNode.data
        const tableData = await dsRef.current.loadTableByServer(newTreeNode.data.title, newTreeNode.data.dataId, "ds")
        if (tableData?.code === 500) {
          return notify(tableData.msg, "error", 2000)
        } else {
          await dsRef.current.reloadTable(tableData, null, null, true, true)
          setPageLoading(false)
          getListsTree()
          return notify("新增成功！", "success", 2000)
        }
      }
    } else {
      setClickItem({})
      setCopyItemData({})
      setPageLoading(false)
      setDir("")
      return notify(newTreeNode.msg, "error", 2000)
    }
  }
  // 修改节点数据
  const editTreeNodeItem = async (params: any) => {
    const editTittle: any = await setEditTreeTittle(params)
    if (editTittle.ok) {
      setDisclosure(params.isDisclosure)
      setLevel(params.isSetLevel)
      setPopupShow(false)
      setSelectData(params)
      initReload(curNodeRef?.current?.title)
      return notify("更新成功", "success", 2000)
    } else {
      console.log(editTittle);
      return notify("更新失败", "error", 2000)
    }
  }
  async function queryTable(params: any) {
    const current = curNodeRef.current;

    const titleName = !current.isIncludeTable ?
      <div >{params.title}<span style={{ color: "red" }}>(此披露项目不包含表格)</span></div> :
      params.title
    setDataName(titleName)
    const lodaTable = await dsRef.current.loadTableByServer(params.title, current.dataId, "ds")
    const verifyData = await dsRef.current.loadVerifyByServer(current.fid + "-zl")
    // dsRef.current.setVerifyData(verifyData)
    dsTableRef.current.zlTableRef.current.setVerifyData(verifyData)
    const zlParams = {
      dbname,
      tid: current.fid,
      type: "zl"
    }
    const lodaTableZl = await queryVerifyStatezl(zlParams)
    if (lodaTableZl.code === 200) {
      getTreesData.map((item: any) => {
        if (item.id === params.id) {
          item.isVerify = lodaTableZl.data
        }
      })
      setTreesData(getTreesData)

      setVerifyResult(verifyData.artParseResultList)
    }
    if (lodaTable?.code === 500) {
      setBtnLoading(false)
      setBtnLoadingId("")
      await dsRef.current.resetTable("ds")
      await dsTableRef.current.zlTableRef.current.resetTable("zl")
      return message.error(lodaTable.msg)
    } else {
      try {
        await dsRef.current.reloadTable(lodaTable, null, null, true, true)
        setBtnLoading(false)
        setBtnLoadingId("")
        setPopupShow(false)
      } catch (error) {
        setBtnLoading(false)
        console.log("表格加载出错了", error);
        return notify("加载出错了！", "error", 2000)
      }
    }
  }

  // 修改节点优化后
  const editTreeNode = async (params: any, isStopUpdateNotesTree?: boolean) => {
    let editTittle: any = {};
    if (!isStopUpdateNotesTree) {
      editTittle = await setEditTreeTittle(params)
    }
    const newId = editTittle?.data ? editTittle?.data : null;
    if (editTittle.ok || isStopUpdateNotesTree) {
      setSelectData(params)
      if (params.isIncludeTable !== undefined) {
        getTreesData.map((item: any) => {
          if (item.id === params.id) {
            item.isIncludeTable = params.isIncludeTable
            if (newId) {
              item.id = newId;
              item.fid = newId;
            }
          }
          if (item.pid === params.id && newId) {
            item.pid = newId;
          }
        })
        setIncludeTables(params.isIncludeTable)
      } else if (params.isDisclosure !== undefined) {
        getTreesData.map((item: any) => {
          if (item.id === params.id) {
            item.isDisclosure = params.isDisclosure
            if (newId) {
              item.id = newId;
              item.fid = newId;
            }
          }
          if (item.pid === params.id && newId) {
            item.pid = newId;
          }
        })
      } else if (params.isSetLevel !== undefined) {
        getTreesData.map((item: any) => {
          if (item.id === params.id) {
            item.isSetLevel = params.isSetLevel
            if (newId) {
              item.id = newId;
              item.fid = newId;
            }
          }
          if (item.pid === params.id && newId) {
            item.pid = newId;
          }
        })
      } else if (params.title !== undefined && params.fid === undefined) {
        getTreesData.map((item: any) => {
          if (item.id === params.id) {
            item.title = params.title
            item.dataId = params.Data_ID;
            if (newId) {
              item.id = newId;
              item.fid = newId;
            }
          }
          if (item.pid === params.id && newId) {
            item.pid = newId;
          }
        })
      }
      setTreesData(getTreesData)
      await queryTable(params)
      if (newId) {
        params.id = newId;
        params.fid = newId;
      }
      setSelectData(params)
      return notify("更新成功！", "success", 2000)
    } else {
      return notify("更新失败！", "error", 2000)
    }
  }
  // 节点移动
  const moveNodeElement = async (params: any, id: any) => {
    setPageLoading(true)
    const moveNode: any = await moveTreeNodePage(params, id)
    if (moveNode.ok) {
      message.success("操作成功！")
      setPageLoading(false)
      getListsTree()
    } else {
      setPageLoading(false)
      message.error("操作失败！！！ 请稍后重试 ！")
    }
  }
  // 获取报表项目
  const getReportList = async (param: boolean) => {

    const params = {
      dbName: dbname,
      year: getDataIds
    }
    const reportList: any = await fetchReportList(params)
    setModalOpen(param)
    if (!reportList.ok) {
      return message.error("暂无报表项目!!!")
    } else {
      const list = reportList.data.filter((item: any) => {
        item.key = item.itemName
        item.title = item.itemName
        item.children = reportList.data.filter((e: any) => {
          e.key = e.itemName
          e.title = e.itemName
          return item.code === e.pCode
        })
        return !item.pCode
      })
      return setDataSource(list)
    }
  }

  // 右键菜单 获取数据
  const treeViewItemContextMenu = (item: any) => {
    curNodeRef.current = item.itemData;
    liftingNodeRef.current = item;
    setDisclosure(curNodeRef.current.isDisclosure)
    setIncludeTables(curNodeRef.current.isIncludeTable)
    setLevel(curNodeRef.current.isSetLevel)
    setProjectName(curNodeRef.current.associatedReport)
    locationName.current=curNodeRef.current.location=== null || curNodeRef.current.pid !==null?"": `附注${curNodeRef.current.location}`
    if (curNodeRef.current.associatedReport) {
      if (curNodeRef.current.associatedReport === "其它披露项目") {
        setOtherCheck(true)
        setReportChecks([])
        setProjectName(curNodeRef.current.associatedReport)
      } else {
        const nodeArr = curNodeRef.current.associatedReport.split(",")
        setOtherCheck(false)
        setReportChecks(nodeArr)
        // setProjectName(curNodeRef.current.associatedReport)
      }
    }

  }

  // 右键操作 事件 优化修改 是否包含 表格
  const includeTableFun = () => {
    const paramData = curNodeRef.current
    const params = {
      dbName: dbname,
      isIncludeTable: !paramData.isIncludeTable,
      id: paramData.id,
      title: paramData.title
    }
    editTreeNode(params)
  }
  // 切换披露表
  const selectItem = async (e: any) => {
    console.log("左键点击--节点选择", e)
    const currentSelData = e.itemData;
    /**
     * @return {
     * - 清除标记
     * - 设置整理tid dataId
     * - 当前选中值
     * - 不包含表格title 设置
     * - 获取表格 设置表格
     * }
    */

    if (e.itemData.id !== btnLoadingId) {
      console.warn("整理前后ref", dsTableRef, dsRef);
      console.log("是否弹出提示", dsRef.current.tableContentIsChange);
      setContent(false)
      setDir("sel")
      if (dsRef?.current?.tableContentIsChange || dsTableRef?.current?.zlTableRef?.current?.tableContentIsChange) {
        confirm({
          title: '提示',
          icon: "",
          content: '是否保存当前披露表内容？',
          onOk() {
            console.log("确认重置", dsRef.current.tableContentIsChange);
            dsRef.current.tableContentIsChange = false
            dsTableRef.current.zlTableRef.current.tableContentIsChange = false
            console.log("确认重置", dsRef.current.tableContentIsChange);
            // eslint-disable-next-line @typescript-eslint/no-use-before-define
            dbTableSave()
          },
          onCancel() {
            // console.log('Cancel');
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            dsRef.current.tableContentIsChange = false
            dsTableRef.current.zlTableRef.current.tableContentIsChange = false
            console.log("取消重置", dsRef.current.tableContentIsChange);
          },
        })
      } else {
        setSelectData(e.itemData)
        setClickItem(e.itemData)
        curNodeRef.current = e.itemData
        const obj = {
          tid: e.itemData.fid,
          data_id: e.itemData.dataId,
        }
        setNoteProps(obj)
        dsRef.current.articulationVerifyService.clearArtVerifyMark()
        setPageLoading(true)

        const titleName = !e.itemData.isIncludeTable ?
          <div >{e.itemData.title}<span style={{ color: "red" }}>(此披露项目不包含表格)</span></div> :
          e.itemData.title
        setDataName(titleName)
        dsTableRef.current.zlTableRef.current.tableConfig = {}
        // getTreesData.map((c: any) => {
        //   if (e.itemData.id === c.id) {
        //     dsTableRef.current.setTitleEditorContent(c.disclosureContent)
        //     dsTableRef.current.setContentEditorContent(c.disclosureContentNote)
        //     dsTableRef.current.setTitleEditorPreviewContent(c.disclosureContent)
        //     dsTableRef.current.setContentEditorPreviewContent(c.disclosureContentNote)
        //   }
        // })
        if (e.itemData.id !== clickItem?.id) {
          if (dsTableRef.current?.handleSetTabValue) {
            dsTableRef.current?.handleSetTabValue()
          }
          dsTableRef.current.onShowBar()
        }
        try {
          const result = await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(dsTableRef.current.zlTableRef.current.articulationVerifyService.artVerifyFormulaList, dsRef.current)
          dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList = result
        } catch (error) {
          return message.error("勾稽计算错误！")
        }
        //切换节点前先重置一下当前表格状态
        await dsRef.current.resetTable();
        const lodaTable = await dsRef.current.loadTableByServer(e.itemData.title, e.itemData.dataId, "ds")
        console.log(lodaTable, 'lodaTable----');
        const dc = getCpasDescByCategory(E_CpasTableDescCategory.DC, lodaTable.cpasDesc)
        const dcn = getCpasDescByCategory(E_CpasTableDescCategory.DCN, lodaTable.cpasDesc)
        dsTableRef.current.setTitleEditorContent(dc ? dc.describe : "");
        dsTableRef.current.setContentEditorContent(dcn ? dcn.describe : "")

        const verifyData = await dsRef.current.loadVerifyByServer(e.itemData.fid + '-zl')
        const zlParams = {
          dbname,
          tid: e.itemData.fid,
          type: "zl"
        }
        const lodaTableZl = await queryVerifyStatezl(zlParams)
        if (lodaTableZl.code === 200) {
          dsTableRef.current.zlTableRef.current.setVerifyData(verifyData)
          setVerifyResult(verifyData.artParseResultList)
        }
        console.log("wss获取整理下的", lodaTableZl);
        // dsRef.current.setVerifyData(verifyData)
        setVerifyResult(verifyData.artParseResultList)

        if (lodaTable?.code === 500) {
          setPageLoading(false)
          await dsRef.current.resetTable("ds")
          await dsTableRef.current.zlTableRef.current.resetTable("zl")
          return message.error(lodaTable.msg)
        } else {
          setPageLoading(false)
          try {
            await dsRef.current.reloadTable(lodaTable, null, null, true, true)
          } catch (error) {
            console.info(error);
            confirm({
              title: '提示',
              icon: "",
              content: '当前披露表数据存在问题，请重新添加数据！',
              async onOk() {
                await dsRef.current.resetTable("ds")
                await dsTableRef.current.zlTableRef.current.resetTable("zl")
                dsRef.current.tableContentIsChange = false
                // eslint-disable-next-line @typescript-eslint/no-use-before-define
                dbTableSave(currentSelData)
              },
              onCancel() { },
            })
          }
        }
      }
    } else {
      return notify("请先等待保存完成后，再进行操作！", "error", 2000)
    }
  }

  /**
   *
   */
  const initByTemplate = async () => {
    const current = curNodeRef.current;
    const title = current.title;
    // const notes_tree_id = current.id;
    const result = await getTemplateInfo(zcbfid);
    const type = "ds"
    const dataId = await getDataId();
    const tableNames = [title];
    if (result.ok) {
      const templateName = result.data?.AuditReportTemplate;

      const response_cpasData = await queryCpasTableByMb(dbname, templateName, tableNames, type);

      if (!response_cpasData.data) {
        return notify(`未在'${templateName}'模板中找到'${title}'披露表 , 因此未进行初始化`, "error", 4000)
        // return notify(`未找到该模板:${title}`, "info", 4000)
      }

      const response = await singleDSTableInit(dbname, templateName, tableNames, type, dataId);

      if (response.ok) {
        // const data = await getLeftTreeList(dbname, dataId);
        // setTreesData(dataTree)
        // setSelectData(curNodeRef.current);
        await initReload(curNodeRef.current.title)
        // leftTreeRef.current?.instance.selectItem(curNodeRef.current);
        //     await selectItem({
        //       itemData: curNodeRef.current,
        // });
        if(searchValue) {
          onSearchValueChanged({
            value: searchValue
          });
        }
        return notify(`${title}模板初始化成功`, "success", 4000)
      } else {
        return notify(response.msg, "error", 4000)
      }
    }
  }

  // 右键列表
  const menuItems = [
    {
      //id: "不披露该附注",
      text: '不披露该附注',
      onItemClick: async () => {
        const paramData = curNodeRef.current
        const params = {
          dbName: dbname,
          isDisclosure: !paramData.isDisclosure,
          id: paramData.id,
          title: paramData.title
        }
        //  TODO
        editTreeNode(params)
      },
      icon: !disclosure,
    },
    {
      text: '不包含表格',
      onItemClick: () => {
        includeTableFun()
      },
      icon: !includeTables
    },
    {
      text: "不设级次",
      onItemClick: async () => {
        const paramData = curNodeRef.current
        const params = {
          dbName: dbname,
          isSetLevel: !paramData.isSetLevel,
          id: paramData.id,
          title: paramData.title
        }
        // TODO
        editTreeNode(params)
      },
      icon: !level,
    },
    {
      //text: `报表项目: ${projectName}`,
      text: (
        <Tooltip title={`报表项目: ${projectName}`} placement="rightTop" >
          {`报表项目: ${projectName}`}
        </Tooltip>
      ),
      onItemClick: () => {
        getReportList(true)
        // setModalOpen(true)
      }
    },
    {
      text: ( <Tooltip placement="rightTop" >
              {`生成位置: ${locationName.current}`}
             </Tooltip>),
      onItemClick: (e:any) => {
        if (curNodeRef.current.pid ===null) {
          setTimeout(() => {

            setIsOpenWordlocation(true)

          }, 500);

          return true
        }  else {
          message.error("只有顶级节点可以设置")
        }


      }
      // disabled: true
    },
    {
      text: '自定义添加',
      items: [
        {
          text: "上方添加",
          onItemClick: () => {
            setTimeout(() => {
              setPopupShow(true)
              setTableName("")
              setDir("up")
            }, 200);
          },
        },
        {
          text: "下方添加",
          onItemClick: () => {
            setTimeout(() => {
              setPopupShow(true)
              setTableName("")
              setDir("down")
            }, 200);

          },
        },
        {
          text: "子级",
          onItemClick: () => {
            setTimeout(() => {
              setPopupShow(true)
              setTableName("")
              setDir("child")
            }, 200);
          }
        }
      ]
    },
    {
      text: '模板库添加',
      onItemClick: _.debounce(async () => {
        // setIsRightTemplateAdd(true);
        setTemplateModalShow(true);
        let data = await getSeekAuditReportTemplate({ zcbfid });
        console.log('当前模板：', data.data.AuditReportTemplate);
        const templateName = data.data.AuditReportTemplate;
        templateRef.current.showTemplate({ templateName });
      }, 100)
    },
    {
      text: '移动',
      items: [
        {
          text: "上移",
          onItemClick: async () => {
            const childData = liftingNodeRef.current
            const dbData = curNodeRef.current
            if (childData.itemData.pid === null && childData.itemData.orderNo === 1) {
              return message.warning("不可上移")
            }
            else if (childData.node.parent?.children[0].key === dbData.id) {
              return message.warning("不可上移")
            }
            else {
              const params = {
                dbName: dbname,
                target: {
                  pid: dbData.parentId,
                  orderNo: dbData.orderNo - 1
                }
              }
              moveNodeElement(params, dbData.id)
            }

          }
        },
        {
          text: "下移",
          onItemClick: async () => {
            const dbData = curNodeRef.current
            const childData = liftingNodeRef.current
            const list = getTreesData.filter((item: any) => item.pid === null)
            if (list[list.length - 1].id === dbData.id) {
              return message.warning("不可下移")
            } else if (childData.node.parent?.children[childData.node.parent?.children.length - 1].key === dbData.id) {
              return message.warning("不可下移")
            } else {
              const params = {
                dbName: dbname,
                target: {
                  pid: dbData.parentId,
                  orderNo: dbData.orderNo + 1
                }
              }
              moveNodeElement(params, dbData.id)
            }
          }
        },
        {
          text: "升级",
          onItemClick: async () => {
            const parentNode = liftingNodeRef.current
            if (parentNode.node.parent) {
              const liftingPid = parentNode.node.parent?.parent ? parentNode.node.parent?.parent.itemData.id : null
              const params = {
                dbName: dbname,
                target: {
                  pid: liftingPid,
                  orderNo: parentNode.node.parent?.itemData.orderNo + 1
                }
              }
              moveNodeElement(params, liftingNodeRef.current.itemData.id)
            } else {
              return message.error("不可升级")
            }
          },
        },
        {
          text: "降级",
          onItemClick: async () => {
            const data = liftingNodeRef.current
            const current = curNodeRef.current
            console.log(data, current);
            if (current.orderNo === 1) {
              return message.warning("不可降级")
            } else {
              console.log(getTreesData);
              let nullIndex = 0
              const nodeNull = getTreesData.filter((item: any) => item.pid === current.pid)
              nodeNull.map((m: any, index: number) => {
                if (m.id === current.id) {
                  nullIndex = index
                }
              })
              const nodeChild = getTreesData.filter((f: any) => nodeNull[nullIndex - 1].id === f.pid)
              console.log(nodeChild);
              const params = {
                dbName: dbname,
                target: {
                  pid: nodeNull[nullIndex - 1].id,
                  orderNo: nodeChild.length === 0 ? 1 : nodeChild[nodeChild.length - 1].orderNo + 1
                }
              }
              console.log(params);
              moveNodeElement(params, current.id)
            }
          },
        }
      ]
    },
    {
      text: '删除',
      onItemClick: async () => {
        const current = liftingNodeRef.current;
        console.warn(current);
        deleteTreeFun(current.itemData.id)
      },
    },
    {
      text: "从模板初始化该表",
      onItemClick: async () => {
        await initByTemplate();
      }
    },
    {
      text: "重命名",
      onItemClick: async () => {
        setTimeout(() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          setPopupShow(true)
          const current = curNodeRef.current;
          setTableName(current.title)
          setOldTableName(current.title);
          setDir("rename")
        }, 500);
      }
    },
    {
      text: "复制",
      onItemClick: () => {
        const parentData = liftingNodeRef.current
        setCopyItemData(parentData)
        return message.success("已复制")
      }
    },
    {
      text: "粘贴",
      onItemClick: async () => {
        const parentData = curNodeRef.current
        if (!copyItemData.itemData) {
          return message.warning("请先复制披露项目")
        }
        const upData = {
          dbName: dbname,
          ...copyItemData.itemData,
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          title: `${copyItemData.itemData.title}-副本${rand(1000, 9999)}`,
          parentId: parentData.parentId,
          pid: parentData.parentId,
          orderNo: parentData.orderNo + 1,
        }
        const pasteNode = await addTreeNodePage(upData);
        if (pasteNode.ok) {
          const pasteTable = await copyCpasTableFun({
            dbname,
            tid: copyItemData.itemData.fid,
            grid_data_type: "source",
            data_type: "json",
            type: "ds"
          })
          if (pasteTable.ok) {
            pasteTable.data.tableConfig = JSON.parse(pasteTable?.data.tableConfig)
            const newTable = await dsRef.current.gridService.resetCpasTableId(pasteTable?.data)
            await dsRef.current.reloadTable(newTable, null, null, true, true)
            await dsTableRef.current.handleSaveData(pasteNode.data.title, pasteNode.data.fid, pasteNode.data.dataId)
          }
          getListsTree()
          setCopyItemData({})
          return message.success("复制成功")
        } else {
          setCopyItemData({})
          return message.error(pasteNode.msg)
        }
      }
    },
  ]
  // 随机数
  const rand = (max: number, min: number) => {
    return Math.floor(Math.random() * (max - min)) + min
  }
  //
  // 生成位置点击事件
  let selectTitle=(e:any)=> {

    const param = {
      dbName: dbname,
      location:e.itemData.ID,
      id: curNodeRef.current.id,

    }
    reportLocation.current=param

  }

  // tree 数据
  const newNodeTree = () => {
    const nodeTree = getTreesData.filter((item: any) => {
      delete item.children
      item.children = getTreesData.filter((c: any) => {
        return c.pid === item.id
      })
      return !item.pid
    })
    return nodeTree
  }
  function findNodeTree(tree: any, func: any) {
    for (const node of tree) {
      if (func(node)) return node
      if (node.children) {
        const result: any = findNodeTree(node.children, func)
        if (result) return result
      }
    }
    return null
  }
  const deleteTreeFun = (child: any) => {
    const newTree = newNodeTree()
    const fv = findNodeTree(newTree, (node: any) => {
      return node.id === child
    })
    console.warn("找出的点", fv);
    deepLoop([fv])
  }
  // 删除披露表增加递归循环
  const deepLoop = (node: any) => {
    console.error("node", node);
    node.map(async (item: any) => {
      deepLoop(item.children)
      const deleteTable = await dsTableRef.current.handleRemoveData(item.title, item.dataId)
      console.log("删除表格数据", deleteTable);
      const delTree: any = await delTreeNodePage(item.id, dbname);
      if (delTree.ok) {
        initReload(curNodeRef?.current?.title)
        return notify("披露项目已删除！", "success", 2000)
      } else {
        return notify(delTree.ms, "error", 2000)
      }
    })
  }
  //  扩展 功能
  const menuItemFun = async (params: any) => {
    if (params === "synchronous") {
      const BusID = "附注";
      const tag = "note";
      setPageLoading(true);
      EntrySynchronizationMethod({
        usercode, password, zcbfid, BusID, tag
      });
      clearTimeout(loadingTimerId);
      const timer = setTimeout(() => {
        notify("未收到同步结果", "error")
        setPageLoading(false);
      }, 120000);
      setLoadingTimer(timer);
      return;
    }
    setDbOrExcel(params)
    if (params === "template") {
      let data = await getSeekAuditReportTemplate({ zcbfid });
      console.log('当前模板：', data.data.AuditReportTemplate);
      const templateName = data.data.AuditReportTemplate;
      templateRef.current.showTemplate({ templateName });
    }
    else if (params === "isScree") {
      console.log(params, 'params 筛选不勾稽项目', menuItem);
      if (menuItem.isScree) {
        initReload()
      } else {
        const screeTreeData = getTreesData.filter((item: any) => item.isVerify === false);
        const resTreeData = sortTreeByChildren(screeTreeData, treeDataList);
        setTreesData([...resTreeData]);
      }
    }
    else if (params === "isShow") {
      setMenuItem({
        ...menuItem,
        isAlwaysShow: true
      })
      const dbTable = getTreesData.filter((item: any) => {
        if (item.isAlwaysShow) {
          defaultCheckedKey.push(item.id)
          setDefaultCheckedKey([...defaultCheckedKey])
        }
        item.key = item.id
        item.children = getTreesData.filter((child: any) => {
          child.key = child.id
          return item.id === child.pid
        })
        return !item.pid
      })
      return setMenuList(dbTable)
    }
    else if (params === "templateSave") {
      saveRef.current.showTemplate()
    }
    else if (params === "reset") {
      confirmDialogRef.current.show({
        args: {
          title: "批量重算",
        },
        okCallback: (r: boolean) => {
          if (r) {
            dsRef.current.hyperFormulaService.clearCache()
            setPercentNum(0)
            setInit(params);
          }
        },
      })
    }
    else if (params === "clearData") {
      // dsRef.current.hyperFormulaService.clearCache()
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      setInit(params)
    }
    else if (params === "init") {

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      initTemplate("")
    }
    else if (params === "export") {
      exportRef.current.openExportDBDialog();
    }else if(params === "exportZLExcel" || params === "exportExcel") {
      exportRef.current.openExportExcelDialog(params);
    }
    else if (params === "import") {
      const successCallback=() => {
        initReload(curNodeRef?.current?.title);
      }
      exportRef.current.openImportDBDialog(successCallback);
    }
    else if (params === "importExcel") {
      importExcelRef.current.openImportDialog("附注");
    }
    else if (params === "break") {
      confirmDialogRef.current.show({
        args: {
          title: "批量断开公式",
        },
        okCallback: async (r: boolean) => {
          if (r) {
            const batchParams = {
              dbname,
              data_id: getDataIds,
              action: "off"
            }
            setPageLoading(true);
            const batchClose = await menuTemplateBatch(batchParams)
            setPageLoading(false);
            if (batchClose.code === 200 && batchClose.ok) {
              await initReload()
              return notify("操作成功！", "success", 2000)
            } else {
              return notify(batchClose.msg, "error", 2000)
            }
          }
        },
      })
    }
    else if (params === "restore") {
      confirmDialogRef.current.show({
        args: {
          title: "批量恢复公式",
        },
        okCallback: async (r: boolean) => {
          if (r) {
            const batchParams = {
              dbname,
              data_id: getDataIds,
              action: "on"
            }
            setPageLoading(true);
            const batchOpen = await menuTemplateBatch(batchParams)
            setPageLoading(false);
            if (batchOpen.code === 200 && batchOpen.ok) {
              await initReload()
              return notify("操作成功！", "success", 2000)
            } else {
              return notify(batchOpen.msg, "error", 2000)
            }
          }
        },
      })
    }
    else if (params === "excel") {
      setMenuItem({
        ...menuItem,
        exportOpen: true
      })
    }
  }
  const items: MenuProps["items"] = dataMenu(leftTreeRef, menuItemFun, setMenuItem, menuItem)
  // 打开勾稽校验详情
  const openDetail = async (e: any, parentItem: any, noVerifyModal?: boolean) => {
    console.log(parentItem, 'parentItem---');
    parentItem.itemData = {
      ...parentItem,
    };
    curNodeRef.current = parentItem;
    // setSelectData(curNodeRef.current);
    await initReload(curNodeRef.current.title)
    //控制校验详情弹窗
    if(!noVerifyModal) {
      setOpenDetails(true)
    }
    const obj = {
      tid: parentItem.fid,
      data_id: parentItem.dataId,
    }
    setSelectData(parentItem.itemData);
    setClickItem(parentItem.itemData);
    // setNoteProps(obj)
    dsRef.current.articulationVerifyService.clearArtVerifyMark();
    console.log(dsTableRef?.current?.state?.tabValue, 'dsTableRef?.current?.state?.tabValue-');
    if (+dsTableRef?.current?.state?.tabValue === 1) {
      setTimeout(() => {
        dsTableRef.current.tabModelChanges("2");
      }, 300);
    }
    if(e) {
      e.stopPropagation();
    }
  }
  // 关闭勾稽校验详情
  const closeDetail = () => {
    setOpenDetails(false)
  }
  const onDragChange = (e: any) => {
    if (e.fromComponent === e.toComponent) {
      const fromNode = findNode(getTreeView(e.fromData), e.fromIndex);
      const toNode = findNode(getTreeView(e.toData), calculateToIndex(e));
      if (toNode !== null && isChildNode(fromNode, toNode)) {
        e.cancel = true;
      }
    }
  }
  function findNode(treeView: any, formIndex: string | number) {
    const nodeElement = treeView.element().querySelectorAll('.dx-treeview-node')[formIndex]
    if (nodeElement) {
      return findNodeById(treeView.getNodes(), nodeElement.getAttribute('data-item-id'))
    }
    return null

  }
  function getTreeView(e: string) {
    return e === "driveC" ? leftTreeRef.current.instance : ""
  }
  function calculateToIndex(e: any) {
    if (e.fromComponent !== e.toComponent || e.dropInsideItem) {
      return e.toIndex
    }
    return e.fromIndex >= e.toIndex ? e.toIndex : e.toIndex + 1
  }
  function isChildNode(p: { itemData: { id: any; }; }, c: { parent: any; }) {
    let { parent } = c
    while (parent !== null) {
      if (parent.itemData.id === p.itemData.id) {
        return true
      }
      parent = parent.parent
    }
    return false
  }
  function findNodeById(node: string | any[], id: any) {
    for (let i = 0; i < node.length; i += 1) {
      if (node[i].itemData.id === id) {
        return node[i]
      }
      if (node[i].children) {
        const nodes: any = findNodeById(node[i].children, id)
        if (nodes != null) {
          return nodes
        }
      }
    }
  }
  /**
   * @params { isDropInsideItem: false 同级节点调整 true 子级节点调整}
   */
  const moveNode = async (fromNode: any, toNode: any, isDropInsideItem: any) => {
    const params = {
      dbName: dbname,
      target: {}
    }
    console.log("拖动", fromNode, toNode, isDropInsideItem);
    if (fromNode?.key === toNode?.key) {
      // 当前节点移动
      return
    } else if (toNode === null) {
      // 最后一个节点移动
      const parentList = getTreesData.filter((item: any) => item.pid === null)
      params.target = {
        pid: parentList[parentList.length - 1].pid,
        orderNo: parentList[parentList.length - 1].orderNo
      }
    } else if (!isDropInsideItem && !toNode.parent) {
      params.target = {
        pid: toNode.parent,
        orderNo: toNode.itemData.orderNo
      }
    } else if (!isDropInsideItem && toNode.parent) {
      params.target = {
        pid: toNode.parent.key,
        orderNo: toNode.itemData.orderNo
      }
    } else {
      // 移动到子级
      if (toNode.children.length > 0) {
        const maxOrderNo: any = []
        toNode.children.map((item: any) => {
          maxOrderNo.push(item.itemData.orderNo)
        })
        params.target = {
          pid: toNode.itemData.id,
          orderNo: Math.max(...maxOrderNo) + 1
        }
      } else {
        params.target = {
          pid: toNode.itemData.id,
          orderNo: 1
        }
      }
    }
    setPageLoading(true)
    const moveNodeData: any = await moveTreeNodePage(params, fromNode.itemData.id)
    if (moveNodeData.ok) {
      setPageLoading(false)
      getListsTree()
      return message.success('更新成功')
    } else {
      setPageLoading(false)
      getListsTree()
      return message.success(moveNodeData.msg)
    }
  }
  const onDragEnd = (e: any) => {
    if (e.fromComponent === e.toComponent && e.formIndex === e.toIndex) {
      return
    }
    const formTreeView = getTreeView(e.fromData)
    const toTreeView = getTreeView(e.toData)
    const fromNode = findNode(formTreeView, e.fromIndex)
    const toNode = findNode(toTreeView, calculateToIndex(e))
    if (e.dropInsideItem && toNode !== null && !toNode.itemData.isDirectory) {
      return
    }
    moveNode(fromNode, toNode, e.dropInsideItem)
  }
  const itemTemplate = (m: any) => {
    return <React.Fragment>
      <Spin spinning={m.id === btnLoadingId} indicator={antIcon}>
        {<div
          className={`item-render ${m.id === curNodeRef.current.id ? 'item-bg' : ""}`}
        >
          <div className="render-icon" style={{ color: m.isEmpty ? "#999" : "none" }}>
            <span className="icon-table">
              {
                !m.isIncludeTable ?
                  <CpasIcon type={"icon-wubiaoge1"} fontSize={18} /> :
                  <CpasIcon type={m.icon} fontSize={18} />
              }
            </span>
            <Tooltip title={!m.isSetLevel ? m.title + "【不设级次】" : m.title} placement="rightTop" >
              {m.title}
            </Tooltip>
          </div>
          <span className="render-span">
            {
              m.isVerify === null || m.isVerify || m.isVerify === undefined ?
                ""
                : <WarningOutlined onClick={(e) => openDetail(e, m)} />
            }
          </span>
        </div>
        }
      </Spin>
    </React.Fragment>
  }
  // 右键菜单 模板
  const menuTemplate = (t: any) => {
    return <div className="menu-template">
      <div className="menu-icon">
        <span>{t.icon && <CheckOutlined />}</span>
      </div>
      <div className="menu-text-content"> <span className="menu-text">{t.text}</span>{t.items && <span className="dx-menu-item-popout" />} </div>
    </div>
  }
  const contextMenuItemClick = (e: any) => {
    if (e.itemData.onItemClick) {
      return e.itemData.onItemClick(e)
    }
  }
  const addNodeData = () => {
    setTableName("")
    setPopupShow(true)
    if (dir === "sel") {
      setDir("sel")
    } else {
      setDir("")
    }
  }
  // 显示隐藏报表为零的项目
  const checkTable = async () => {
    if (isOpenEye) {
      const dateId = await getDataId();
      const res = await getReportItemsZero({ partId: zcbfid, dataId: dateId });
      console.log(res, '查询报告基础数据为0的节点');
      const reportItemsZeroData = res && res.data ? res.data : null;
      let newTreesData = [];
      const delIds: any = [];
      for (let i = 0; i < getTreesData.length; i++) {
        const treeItem = getTreesData[i];
        if (reportItemsZeroData && reportItemsZeroData.length) {
          for (let j = 0; j < reportItemsZeroData.length; j++) {
            const reportItems = reportItemsZeroData[j];
            if (treeItem.id === reportItems.id || treeItem.pid === reportItems.pid) {
              delIds.push(treeItem.id);
            }
          }
        }
      }

      newTreesData = getTreesData.filter((item: any) => {
        return !delIds.includes(item.id);
      });
      console.log(newTreesData, 'newTreesData 展示不为0的节点数据', delIds);
      setTreesData(newTreesData);
    } else {
      getListsTree()
    }
  }

  useEffect(() => {
    if (isState && lastCurNodeRef.current) {
      curNodeRef.current = _.cloneDeep(lastCurNodeRef.current);
      lastCurNodeRef.current = null;
      leftTreeRef.current?.instance.selectItem(curNodeRef.current);
    }
  }, [isState])

  // 左侧 展开 收起
  const initPageCon = () => {
    return <React.Fragment>
      <div>
        <i className="icon-right block" onClick={() => {
          if (!lastCurNodeRef.current) {
            lastCurNodeRef.current = _.cloneDeep(curNodeRef.current);
          }
          setIsState(!isState)
        }} />
      </div>
    </React.Fragment>
  }

  // 执行双表保存
  const dbTableSave = async (currentSelData?: any) => {
    setBtnLoading(true)
    dsRef.current.tableContentIsChange = false
    dsTableRef.current.zlTableRef.current.tableContentIsChange = false
    // console.log("双表保存执行", dsRef.current.tableContentIsChange);
    // console.log("获取当前list", dsRef.current.articulationVerifyService.artVerifyFormulaList);
    const contentTitle = dsTableRef.current.getTitleEditorContent();
    const content = dsTableRef.current.getContentEditorContent();
    const displayData = dsRef.current?.hot.getData();
    const saveNotesData = currentSelData ? currentSelData : selectData;
    //获取整理下最新的content数据
    // let zlContent = content;  //默认等于设计模式下的数据
    // try {
    //   const zlContentNoteResponse = await parseFormulaByContentApi({
    //     content: content,
    //     displayData
    //   });
    //   if(zlContentNoteResponse.ok){
    //     zlContent = zlContentNoteResponse.data;
    //   }
    // }catch (e) {
    //   console.error(e);
    // }
    const params = {
      dbName: dbname,
      title: saveNotesData.title,
      id: saveNotesData.id,
      fid: saveNotesData.fid,
      // disclosureContentNote: content,
      // disclosureContent:contentTitle,
      // zlDisclosureContent:contentTitle,
      // zlDisclosureContentNote:zlContent,
    }
    setBtnLoadingId(saveNotesData.id)
    setTitleAndContent({
      ...titleAndContent,
      title: contentTitle,
      content: content
    })
    try {
      const result = await dsTableRef.current.zlTableRef.current.articulationVerifyService.parseArtVerifyFormula(dsTableRef.current.zlTableRef.current.articulationVerifyService.artVerifyFormulaList, dsRef.current)
      dsTableRef.current.zlTableRef.current.articulationVerifyService.artParseResultList = result
      console.log(result);
    } catch (error) {
      notify(error, "error", 2000)
    }
    console.log(selectData, 'selectData 当前披露节点数据');
    const current = curNodeRef.current;
    const dbSave = await dsTableRef.current.handleSaveData(saveNotesData.title, saveNotesData.fid || current.fid, saveNotesData.dataId);
    // 更新注释内容，迁移到CpasTable内部处理
    if (dbSave === undefined) {
      editTreeNode(params, true);
    }
    const res = await getNotesIsEmptyAPI({
      dbName: dbname,
      dataId: saveNotesData.dataId,
      tid: current.id
    });
    const isEmpty = res.ok && res.data ? res.data : false;
    console.log(isEmpty, '查询空披露表结果', current?.isEmpty);
    if (isEmpty !== current?.isEmpty) {
      await setEditTreeTittle({
        ...params,
        isEmpty
      });
      await getListsTree(true);
      current.isEmpty = isEmpty;
      leftTreeRef?.current?.instance?.repaint();
    }
  }

  const onSearchValueChanged = async (data: any) => {
    const val = data.value;
    if(val) {
      setSearchValue(val);
      const treesData = await getListsTree(true, val);
      if(!treesData) {
        return;
      }
      const currentTrees = treesData.filter((item: any) => item.title.includes(val));
      if(currentTrees && currentTrees.length) {
        const res = loopParentTreeList(currentTrees, treesData);
        setTreesData(res);
      }
    }else {
      getListsTree();
      setSearchValue("");
    }
  }
  // 右侧 表格
  const rightPageCon = () => {
    return <React.Fragment>
      <CpasTableDs
        title={dataName}
        dsRef={dsTableRef}
        ref={dsRef}
        notes={noteProps}
        initContent={initContent}
        contentText={contentText}
        itemName={projectName}
        type={"ds"}
        initTem={
          dbname
        }
        // dbTableSaveFun={ dbTableSave()}/
        name={dataName}
        onSynchronous={onSynchronous}
      />
    </React.Fragment>
  }
  // 左侧 披露表项目
  const leftPageCon = () => {
    return <React.Fragment>
      <div className="flexCon">
        <div>
          <i className="icon-left block"
            onClick={() => {
              if (!lastCurNodeRef.current) {
                lastCurNodeRef.current = _.cloneDeep(curNodeRef.current);
              }
              setIsState(!isState)
            }} />
        </div>
        <div className="flex-start mr-8">
          <i >
            <PlusOutlined onClick={() => addNodeData()} />
          </i>
          {
            <Tooltip title={isOpenEye ? "隐藏报表数为零的项目" : "显示报表数为零的项目"}>
              <i className={isOpenEye ? "icon-eye block" : "icon-eyes block"}
                onClick={() => {
                  setOpenEye(!isOpenEye)
                  checkTable()
                }}
              />
            </Tooltip>
          }
          <Button type="text" icon={<SaveOutlined />} onClick={() => dbTableSave()} loading={btnLoading} />
          <Dropdown
            menu={{ items }}
            placement="bottomLeft"
            arrow
            trigger={"click"}
          >
            <a onClick={(e) => e.preventDefault()}
              style={{ display: "inline-block", paddingTop: "5px" }}>
              <Space>
                <i className="icon-list block" />
              </Space>
            </a>
          </Dropdown>
        </div>
      </div>
      <div className="mt-8 table-sort left-page-con" style={{ paddingRight: "10px" }}>
        <Sortable
          filter=".dx-treeview-item"
          group="shared"
          data="driveC"
          allowDropInsideItem={true}
          allowReordering={true}
          onDragChange={onDragChange}
          onDragEnd={onDragEnd}>
            <TextBox
              showClearButton={true}
              mode={"search"}
              value={searchValue}
              onValueChanged={(e) => onSearchValueChanged(e)}
            />
          <TreeView
            id="treeviewDriveC"
            // searchEnabled={true}
            // searchValue={searchValue}
            // searchTimeout={300}
            // searchEditorOptions={{
            //   // value: searchValue,
            //   "valueChangeEvent": "change",
            //   "onValueChanged": onSearchValueChanged
            // }}
            expandedExpr="expanded"
            dataStructure="plain"
            ref={leftTreeRef}
            parentIdExpr={"parentId"}
            // dataSource={getTreesData}
            onItemClick={selectItem}
            displayExpr="title"
            itemRender={itemTemplate}
            items={getTreesData}
            virtualModeEnabled={true}
            keyExpr={"id"}
            onItemContextMenu={treeViewItemContextMenu}
          />

        </Sortable>
        <div className="context-menu">
          <ContextMenu
            ref={curNodeRef}
            dataSource={menuItems}
            target="#treeviewDriveC .dx-treeview-item"
            onItemClick={contextMenuItemClick}
            itemRender={menuTemplate}
          />
        </div>
      </div>

    </React.Fragment>;
  }

  // 确认披露表 名称
  const onConfirm = async () => {
    if (!tableName) {
      return notify("不能为空！", "error", 2000)
    }
    if (dir === "rename" && tableName === oldTableName) {
      setPopupShow(false)
      setTableName("")
      return
    }
    if (dsTableRef.current?.handleSetTabValue) {
      dsTableRef.current?.handleSetTabValue()
    }
    const parentData = curNodeRef.current
    await dsRef.current.resetTable("ds", true)
    await dsTableRef.current.zlTableRef.current.resetTable("zl", true)
    const params = {
      dbname: dbname,
      tname: tableName,
      data_id: getDataIds,
      type: "ds"
    }
    const res = await getCpasTableName(params)
    if (res.code === 200 && res.data) {
      return message.warning("披露项目已存在")
    }
    else if (res.code === 200) {
      if (dir === "up") {
        const upData = {
          pid: parentData.parentId,
          orderNo: parentData.orderNo,
          title: tableName,
          ...paramItem
        }
        console.log("up", upData);
        setTopIndex(liftingNodeRef.current.itemIndex)
        newAddTreeNode(upData)
        setTableName("")
      }
      else if (dir === "down") {
        const upData = {
          pid: parentData.parentId,
          orderNo: parentData.orderNo + 1,
          title: tableName,
          ...paramItem
        }
        setTopIndex(liftingNodeRef.current.itemIndex)
        newAddTreeNode(upData)
        setTableName("")
      }
      else if (dir === "child") {
        const parentChild = liftingNodeRef.current
        const upData = {
          pid: parentData.id,
          orderNo: null,
          title: tableName,
          ...paramItem
        }
        const maxOrder: any = []
        if (parentChild.node.children.length > 0) {
          parentChild.node.children.map((item: any) => {
            maxOrder.push(item.itemData.orderNo)
          })
          upData.orderNo = Math.max(...maxOrder) + 1
        } else {
          upData.orderNo = 1
        }
        setTopIndex(liftingNodeRef.current.itemIndex)
        newAddTreeNode(upData)
        setTableName("")
      }
      else if (dir === "sel") {
        paramItem.pid = clickItem?.pid
        paramItem.orderNo = clickItem?.orderNo + 1
        paramItem.title = tableName
        newAddTreeNode(paramItem)
        console.log("item", paramItem);

        setTableName("")

      }
      else if (dir === "") {
        const maxOrderNo: any = []
        getTreesData.map((item: any) => {
          if (item.pid === null) {
            maxOrderNo.push(item.orderNo)
          }
        })
        paramItem.pid = null
        paramItem.orderNo = maxOrderNo.length === 0 ? 1 : Math.max(...maxOrderNo) + 1
        paramItem.title = tableName
        console.log("=", paramItem);
        newAddTreeNode(paramItem)
        setTableName("")
      }
      else if (dir === "rename") {
        const current = curNodeRef.current;
        const p = {
          dbname,
          tid: current.fid,
          name: tableName,
          Data_ID: current.dataId,
        }
        const data = await editCpasTableNames(p)
        if (data?.ok) {
          const param = {
            dbName: dbname,
            title: tableName,
            Data_ID: current.dataId,
            id: current.id,
          }
          await editTreeNode(param)

        } else {
          return message.error("重命名失败")
        }
      }
    }
  }
  // 新增披露表项目名称
  const onChangeName = (e: any) => {
    const value = e.target.value ? e.target.value.trim() : ""
    console.log(value, '新增披露表项目名称');
    setTableName(value)
  }
  // menu菜单
  const onCheck = (val: any) => {
    console.log("点击显示当前值", val);
    const values = [...new Set(val.checked)]
    values.map((k: any) => {
      getTreesData.map((item: any) => {
        if (k === item.id) {
          if (item.pid) {
            if (values.indexOf(item.pid) === -1) {
              values.push(item.pid)
            }
          }
        }
      })
    })
    if (values.length === getTreesData.length) {
      setCheckedAll(true)
    } else {
      setCheckedAll(false)
    }
    // // setCheckedKeys(val.checked)
    setDefaultCheckedKey(values)
  }
  // 常在界面显示
  const onOkConfirm = async () => {
    confirmDialogRef.current.show({
      args: {
        title: "常在界面展示",
        content: "警告！此行为同步后会覆盖其他成员的树形结构。",
      },
      okCallback: async (r: boolean) => {
        if (r) {
          const dateId = await getDataId();
          const params = {
            dbName: dbname,
            dataId: dateId,
            ids: defaultCheckedKey,
          }
          const response: any = await fetchAlwaysShow(params)
          if (response.ok) {
            await getListsTree()
            setMenuItem(menuItem.isAlwaysShow = !menuItem.isAlwaysShow)
            return notify("更新成功！", "success", 2000)
          } else {
            return notify("更新失败！", "error", 2000)
          }
        }
      },
    })

    // defaultCheckedKey.map((item: any) => {
    //   getTreesData.map((t: any) => {
    //     if (item === t.id) {
    //       const params = {
    //         dbName: dbname,
    //         isAlwaysShow: true,
    //         id: item,
    //       }
    //       // TODO
    //       editTreeNodeItem(params)

    //     } else {
    //       const params = {
    //         dbName: dbname,
    //         isAlwaysShow: false,
    //         id: item,
    //       }
    //       // TODO
    //       editTreeNodeItem(params)
    //       setMenuItem(menuItem.isAlwaysShow = !menuItem.isAlwaysShow)
    //     }
    //   })
    // })
  }
  // 模板初始化
  const initTemplate = async (data: any) => {
    setShowTemplateOpen(true)
    const dateIds = await getDataId()
    const res = await getSeekAuditReportTemplate({ zcbfid });
    if (res.success) {
      const resTemp: any = await templateInitApi({
        dbName: dbname,
        templateName: data ? data : res.data.AuditReportTemplate,
        tableNames: [],
        type: 'ds',
        dataId: dateIds,
      });
      if (resTemp.success) {
        //getListsTree()
        let params = {
          dbname,
          data_id: getDataIds,
          type: "vr"
        };
        await getAllTypeData(params);
        await initReload("", "switchTemplate")
        if (+dsTableRef?.current?.state?.tabValue === 2) {
          dsTableRef.current.tabModelChanges("1");
        }
        setShowTemplateOpen(false)
        notify(`模板初始化成功`, "success", 2000);
      } else {
        setShowTemplateOpen(false);
        if (res.data.AuditReportTemplate || data) {
          notify(`${resTemp.msg}`, "error", 2000);
        } else {
          notify(`请在首页组成部分信息内选择报告模板`, "warning", 2000);
        }
      }
    } else {
      setShowTemplateOpen(false)
      notify(`${res.data}`, "error", 2000);
    }
  }
  const onSearchTableName = (e: any) => {
    const newTreeData = getTreesData.filter((item: any) => item.title.includes(e.target.value)).filter((i: any) => {
      i.key = i.id
      i.children = getTreesData.filter((child: any) => {
        child.key = child.id
        return i.id === child.pid
      })
      return !i.pid
    })
    setMenuList(newTreeData)
  };
  const setInit = async (params: any) => {
    setShowOpen(true)
    const clearDB = {
      dbname,
      data_id: getDataIds
    }
    let total = 0
    if (params === "reset") {
      const timer = setInterval(async () => {
        if (total < 100) {
          const res = await queryDataState({ type: "verifyAndCalculate" })
          console.log(res);
          total = parseInt(res.data.process)
          setPercentNum(total)
          setContentMsg(res.data.message)
          if (res.ok && total === 100) {
            await queryResetState({ process: 0, type: "verifyAndCalculate" })
            clearInterval(timer)
          }
        }
      }, 500)
      const data = await reCalculateNotesAPI(clearDB)
      if (data.ok) {
        await initReload()
        setShowOpen(false)
        return message.success("重算成功")
      } else {
        setShowOpen(false)
        return message.error(data.msg)
      }
    } else {
      const timer = setInterval(async () => {
        if (total < 100) {
          const res = await queryDataState({ type: "clear" })
          console.log(res);
          total = parseInt(res.data.process)
          setContentMsg(res.data.message)
          setPercentNum(total)
          if (res.ok && total === 100) {
            await queryResetState({ process: 0, type: "clear" })
            clearInterval(timer)
          }
        }
      }, 500)
      const res = await clearDataAll(clearDB)
      if (res.ok) {
        setShowOpen(false)
        // lzx 取消清空数据后的批量重算
        // await getAllData({
        //   dbname,
        //   data_id: getDataIds,
        //   is_stop_rec: true,
        // })
        await initReload()
        return message.success("清空成功！")
      } else {
        setShowOpen(false)
        return message.success(res.msg)
      }
    }
  }
  const onChangeTreeShow = (e: any) => {
    if (e.target.checked) {
      getTreesData.map((item: any) => {
        return defaultCheckedKey.push(item.key);
      })
      setCheckedAll(true)
      setDefaultCheckedKey([...defaultCheckedKey])
    } else {
      setDefaultCheckedKey([])
      setCheckedAll(false)
    }
  }

  const onSynchronous = async () => {
    const BusID = curNodeRef.current.id;
    const tag = "singleNote";
    let timer: any = null;
    setIsSyncStatus("1");
    setPageLoading(true);
    EntrySynchronizationMethod({
      usercode, password, zcbfid, BusID, tag, BusType: 101
    });

    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      if (isSyncStatus === "1") {
        clearTimeout(timer);
        setIsSyncStatus("2");
      }
    }, 15000);
    // setLoadingTimer(timer);
    return;
  }

  useEffect(() => {
    initReload()
    getYearData()
  }, [])
  const setLoadingCallback = (value: boolean) => {
    console.log(value, 'value---');
    setPageLoading(value);
  }
  return (
    <div>
      <Spin spinning={pageLoading}>
        <div className={'cpas-audit-ds-container'} style={{ height: "calc(100vh - 90px)", overflow: "auto" }}>
          <LayoutB
            rowSize={isState ? initStateSize : stateSize}
            leftSlot={isState ? leftPageCon() : initPageCon()}
            rightSlot={rightPageCon()}
            style={{ overflow: "auto" }}
          />
        </div>
      </Spin>
      <CpasModal ref={exportRef} type="ds" zcbfid={zcbfid} zcbfName={zcbfName} dsTableRef={dsTableRef} loadingCallback={setLoadingCallback} dataId={getDataIds} importOkCallback={() => {return initReload(curNodeRef?.current?.title) }}/>
      <ImportExcelModal ref={importExcelRef} type="ds" title="导入Excel附注" loadingCallback={setLoadingCallback}  dataId={getDataIds} okCallback={() => {return initReload(curNodeRef?.current?.title) }}/>
      <Modal
        title="报表项目"
        open={isModalOpen}
        destroyOnClose={true}
        maskClosable={false}
        onCancel={() => {
          setReportChecks([])
          setMainProject("")
          setModalOpen(false)
        }}
        onOk={() => {
          console.error(reportChecks);
          const param = {
            dbName: dbname,
            associatedReport: reportChecks.join(","),
            id: curNodeRef.current.id,
            fid: curNodeRef.current.fid,
            pid: curNodeRef.current.pid,
            // title: curNodeRef.current.title
          }
          dsRef.current.props = {
            ...dsRef.current.props,
            itemName: reportChecks.join(",")
          }
          editTreeNodeItem(param)
          setModalOpen(false)

        }}
      >
        <div style={{ height: "70vh" }}>
          <Collapse
            defaultActiveKey={['1', "2"]}
            expandIconPosition={"end"}
          >
            <Panel header="其它项目注释" key="1">
              <div style={{ height: "50px", marginLeft: "15px", lineHeight: "50px" }}>
                <Checkbox onChange={(e: any) => {
                  setReportChecks([])
                  setOtherCheck(e.target.checked)
                  if (e.target.checked) {
                    setMainProject("disabled")
                    reportChecks.push("其它披露项目")
                    setReportChecks([...reportChecks])
                  } else {
                    setMainProject("")
                  }
                }} checked={otherCheck} /> <span>其它披露项目</span>
              </div>

            </Panel>
            <Panel header="主要项目注释" key="2" collapsible={mainProject}>
              <div style={{ height: "50vh", overflow: "auto" }}>
                <Tree
                  checkable
                  onCheck={(keys: any) => {
                    setReportChecks(keys.checked)
                  }}
                  disabled={otherCheck}
                  checkedKeys={reportChecks}
                  treeData={dataSource}
                  checkStrictly={true}
                />
              </div>
            </Panel>
          </Collapse>
        </div>
      </Modal>
      <Modal
        title={dir === "rename" ? "重命名" : "添加"}
        open={popupShow}
        maskClosable={false}
        width={380}
        onOk={() => onConfirm()}
        centered
        destroyOnClose
        onCancel={() => {
          setPopupShow(false)
          setTableName("")
        }}
      >
        <div className="popup-name">
          <span>披露表名称: </span>
          <Input
            placeholder="请输入披露表名称"
            size="middle"
            onChange={(e: any) => onChangeName(e)}
            value={tableName}
          />
        </div>
      </Modal>
      <BuildLaction
            isOpenWordlocation={isOpenWordlocation}
            selectTitle={selectTitle}
            closeMadal={()=>{setIsOpenWordlocation(false)}}
            locationName ={curNodeRef.current?.location?curNodeRef.current.location:""}
            editTreeNodeItem={async ()  => { await editTreeNodeItem(reportLocation.current);setIsOpenWordlocation(false)} }
      >
      </BuildLaction>
      {/* 常在界面显示弹框 */}
      <Modal
        open={menuItem.isAlwaysShow}
        title="常在界面展示"
        destroyOnClose
        maskClosable={false}
        onCancel={() =>
          setMenuItem(menuItem.isAlwaysShow = !menuItem.isAlwaysShow)
        }
        onOk={() => onOkConfirm()}
      >
        <div className="pro-list">
          <Checkbox onChange={onChangeTreeShow} checked={checkedAll}>全选</Checkbox>
          <Search
            style={{ marginBottom: 8 }}
            placeholder="请输入要查询的披露表名称"
            onChange={onSearchTableName}
          />
          <Tree
            checkable
            onCheck={onCheck}
            checkedKeys={defaultCheckedKey}
            treeData={menuList}
            checkStrictly={true}
          />
        </div>
      </Modal>
      <Details
        isOpen={openDetails}
        handleOpen={closeDetail}
        params={dsTableRef}
        result={verifyResult}
        isBackAll={false}
        onBackAll={() => { }}
      />
      <TemplateModal
        ref={templateRef}
        title={templateModalShow ? "选择模板" : "切换模板"}
        changeData={{
          cloudTempType: "报告模板",
        }}
        okCallback={async (data: string) => {
          console.log(data, '模板名称');
          // 切换模版
          if (!templateModalShow) {
            initTemplate(data)
            //右键模版库添加
          } else if (data) {
            console.log(curNodeRef?.current?.title, 'curNodeRef.current-----');
            const successCallback=() => {
              initReload(curNodeRef?.current?.title, "switchTemplate");
            }
            exportRef.current.confrimRightTemplateCallback(data, curNodeRef, successCallback);
          }
        }}
        cancelCallback={() => {
          if (templateModalShow) {
            setTemplateModalShow(false);
          }
        }}
      />
      <LoadPanel shadingColor="rgba(0,0,0,0.4)" visible={templateLoadPanelVisible} />
      <TemplateSave
        ref={saveRef}
        saveData={{
          dbname,
          dateId: getDataIds || "",
          tableNames: [],
          type: "ds",
        }}
        okCallback={async (data: any) => {
          console.log(data, "data");
          const params = {
            dbName: dbname,
            templateFile: '',
            tableNames: [],
            templateName: data,
            type: "ds",
            dataId: getDataIds,
          }

          // 设置loading为true
          setTemplateLoadPanelVisible(true);
          const resData = await getTemplateExportToSqlite(params)
          console.log(resData, 'resData----');
          setTemplateLoadPanelVisible(false);
          if (resData.code === 200) {
            return notify("模板保存成功", "success", 2000)
          } else {
            return notify(resData.msg, "error", 2000)
          }
        }}
      />
      <Modal
        open={isShowOpen}
        footer={null}
        centered
        maskClosable={false}
        closable={false}
        title={null}
        className="dot-body"
        wrapClassName="spin-example"
      >
        <Progress percent={percentNum} status="active" style={{ color: "#fff" }} />
        <div className="process-content">
          {contentMsg}
        </div>
      </Modal>
      {/* 模板初始化进度条 */}
      <PageLoading
        isOpen={showTemplateOpen}
        isMaskClose={false}
        content={"正在加载..."}
        width={200}
      />
      <ConfirmDialog ref={confirmDialogRef} />
    </div>
  );
})

export default NotePage;
